package com.keepers.repair.utils;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import com.blankj.utilcode.util.Utils;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * auth aboom
 * date 2018/10/21
 */
public class SpUtils {

    private static SharedPreferences mPreferences;

    private static SharedPreferences getPreferences() {
        if (null == mPreferences) {
            mPreferences = PreferenceManager
                .getDefaultSharedPreferences(Utils.getApp());
        }
        return mPreferences;
    }

    public static void put(String key, Object value) {
        SharedPreferences.Editor edit = getPreferences().edit();
        if (value instanceof String) {
            edit.putString(key, (String) value);
        } else if (value instanceof Boolean) {
            edit.putBoolean(key, (Boolean) value);
        } else if (value instanceof Integer) {
            edit.putInt(key, (Integer) value);
        } else if (value instanceof Float) {
            edit.putFloat(key, (Float) value);
        } else if (value instanceof Long) {
            edit.putLong(key, (Long) value);
        } else if (value instanceof Set) {
            edit.putStringSet(key, (Set<String>) value);
        } else if (value instanceof List) {
            StringBuilder sb = new StringBuilder();
            for (String str : (List<String>) value) {
                sb.append(str);
                sb.append("#$#");
            }
            edit.putString(key, sb.toString());
        } else {
            throw new RuntimeException("Not support type");
        }
        edit.apply();
        edit.clear();
    }

    public static String getString(String key) {
        return getPreferences().getString(key, null);
    }

    public static String getString(String key, String defValue) {return getPreferences().getString(key, defValue);}

    public static Boolean getBoolean(String key) {
        return getPreferences().getBoolean(key, false);
    }

    public static Integer getInteger(String key) {
        return getPreferences().getInt(key, 0);
    }

    public static Float getFloat(String key) {
        return getPreferences().getFloat(key, 0.0f);
    }

    public static Float getFloat(String key, float defaultValue) {return getPreferences().getFloat(key, defaultValue);}

    public static Long getLong(String key) {
        return getPreferences().getLong(key, 0);
    }

    public static Set<String> getStringSet(String key) {return getPreferences().getStringSet(key, null);}

    public static boolean hasKey(String key) {
        return getPreferences().contains(key);
    }

    public static List<String> getStringList(String key) {
        String value = getString(key);
        if (!TextUtils.isEmpty(value)) {
            String[] splitStr = value.split("#\\$#");
            return Arrays.asList(splitStr);
        }
        return null;
    }
}
